var mosca = require('mosca')

var ascoltatore = {
  // using ascoltatore
  // type: 'mongo',
  // url: 'mongodb://localhost:27017/mqtt',
  // pubsubCollection: 'ascoltatori',
  // mongo: {}
}

var settings = {
  port: 1883,
  backend: ascoltatore,
  http: {
    port: 1884,
    bundle: true,
    static: './'
  }
}

var server = new mosca.Server(settings)

// when a client is connected; the client is passed as a parameter.
server.on('clientConnected', function (client) {
  console.log(`用户：${client.id}连接成功\n`)
  // console.log({
  //   clientId: client ? client.id : 'undefined',
  //   event: 'clientConnected'
  // })
})

// when a client is being disconnected; the client is passed as a parameter.
server.on('clientDisconnecting', (client) => {
  console.log(`用户：${client.id}正在断开连接\n`)
  // console.log({
  //   clientId: client ? client.id : 'undefined',
  //   event: 'clientDisconnecting'
  // })
})

// when a client is disconnected; the client is passed as a parameter.
server.on('clientDisconnected', function (client) {
  console.log(`用户：${client.id}断开连接成功\n`)
  // console.log({
  //   clientId: client ? client.id : 'undefined',
  //   event: 'clientDisconnected'
  // })
})

// when a new message is published; the packet and the client are passed as parameters.
server.on('published', function (packet, client) {
  console.log(`用户：${client ? client.id : 'undefined'}向Topic：${packet.topic}发布了：${packet.payload.toString()}\n`)
  // console.log({
  //   clientId: client ? client.id : 'undefined',
  //   topic: packet.topic,
  //   pubMessage: packet.payload.toString(),
  //   event: 'published'
  // })
})

// when a client has sent back a puback for a published message; the packet and the client are passed as parameters.
server.on('delivered', (packet, client) => {
  console.log({
    clientId: client ? client.id : 'undefined',
    topic: packet.topic,
    event: 'delivered'
  })
})

// when a client is subscribed to a topic; the topic and the client are passed as parameters.
server.on('subscribed', (topic, client) => {
  console.log(`用户：${client ? client.id : 'undefined'}订阅了Topic：${topic}\n`)
  // console.log({
  //   clientId: client ? client.id : 'undefined',
  //   topic: topic,
  //   event: 'subscribed'
  // })
})

// when a client is unsubscribed to a topic; the topic and the client are passed as parameters.
server.on('unsubscribed', (topic, client) => {
  console.log(`用户：${client ? client.id : 'undefined'}取消订阅Topic：${topic}\n`)
  // console.log({
  //   clientId: client ? client.id : 'undefined',
  //   topic: topic,
  //   event: 'unsubscribed'
  // })
})

server.on('ready', () => {
  console.log('mqtt服务端Mosca已准备就绪！\n')
})
